﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.APP.Application.Command.Traceability;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrerture.Interfaces;

namespace Traceability.APP.Application.CommandHandle.Traceability
{
    public class GetAddTraceabilityCommonHandle:IRequestHandler<GetAddTraceabilityCommon,APIResult<int>>
    {
        private readonly IBaseRepository<Traceability_Management> TraceabilityDal;
        private readonly IMapper mapper;
        public GetAddTraceabilityCommonHandle(IBaseRepository<Traceability_Management> traceabilityDal, IMapper mapper)
        {
            TraceabilityDal = traceabilityDal;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(GetAddTraceabilityCommon request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            //var rolename = roleRepo.GetAll().Where(x => x.RoleName == request.RoleName && x.IsDeleted == false).FirstOrDefault();
            var tracname = TraceabilityDal.GetAll().Where(x => x.Batch == request.Batch && x.IsDeleted == false).FirstOrDefault();
            if (tracname != null)
            { 
                result.Code = StateCode.Faile;
                result.Message = "该商品已存在溯源信息";
                return Task.FromResult(result);
            }

            var model = mapper.Map<Traceability_Management>(request);
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            { 
                r = TraceabilityDal.Add(model).Result;
                tran.Complete();
            }

            if (r > 0)
            { 
                result.Code = StateCode.Ok;
                result.Message = "商品溯源新增成功";
                return Task.FromResult(result);
            }
            else
            {
                result.Code = StateCode.Ok;
                result.Message = "商品溯源新增失败";
                return Task.FromResult(result);
            }


        }




    }
}
